package com.pengpai.pangucms.utils;

import cn.hutool.core.util.StrUtil;
import com.pengpai.pangucms.DTO.CurrentUser;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

public class UserUtils {

    public static String CurrentUserName(){

        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String currentUserName;
        if (principal instanceof UserDetails) {
            currentUserName = ((UserDetails) principal).getUsername();
        } else {
            currentUserName = principal.toString();
        }
        return currentUserName;
    }

    public static CurrentUser CurrentUser() {

        return (CurrentUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }

    public static String encoder(String pass){

        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();

        if(StrUtil.isNotBlank(pass)){

            return bCryptPasswordEncoder.encode(pass);
        }
        //默认加密123456
        return bCryptPasswordEncoder.encode("123456");
    }

    public static boolean matchs(CharSequence rawPassword, String encodedPassword){
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        return bCryptPasswordEncoder.matches(rawPassword, encodedPassword);
    }
}
